package com.libs.utils;


import com.libs.sys.model.Userseat;
import com.libs.sys.service.LibService;
import com.libs.sys.service.impl.LibServiceImpl;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.impl.client.CloseableHttpClient;

import java.util.Calendar;

@Slf4j
public class MyThread implements Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */

    private Userseat userseat;
    private final LibService libService = new LibServiceImpl();
    private int num = 1;
    private char flag = '0';
    private final int FINISH_MINUTE = 59;
    private final char REQUST = '0';
    String res = "";
    String name = "";
    boolean isLogin = false;
    boolean isSet = false;
    private int count = 5;

    public MyThread(Userseat userseat) {
        this.userseat = userseat;
    }

    @SneakyThrows
    @Override
    public void run() {
        CloseableHttpClient httpClient = HttpClientConn.getHttpClient();
        while (!isLogin && isTime()) {
            name = libService.login(userseat, httpClient);
            isLogin = !"-1".equals(name);
        }
        while (count>0){
            if(isLogin) {
                log.info("{}登录成功", name);
                while (Calendar.getInstance().get(Calendar.MINUTE) < 30 &&
                        Calendar.getInstance().get(Calendar.HOUR) == 5) {
                }
                long begin = System.currentTimeMillis();
                while (REQUST == flag && isTime()) {
                    flag = libService.setSeat(userseat, httpClient);
                    num++;
                }
                long finish = System.currentTimeMillis();
                if (REQUST == flag) {
                    res = "失败";
                } else {
                    res = "成功";
                }
                log.info("【{}】抢座{}={}ms/次--{}次", name, res, (finish - begin) / num, num);
                count--;
            }else{
                log.info("【{}】登录失败", userseat.getUid());
            }
        }

    }

    boolean isTime() {
        return Calendar.getInstance().get(Calendar.HOUR) < 7;
    }
}
